<template>
    <div style="border: 1px solid #ccc; padding: 45px;">
         <el-form :inline="true" :model="formInline" class="search-form">
          <!-- 第一行 -->
          <el-form-item label="货品">
            <el-input 
              v-model="formInline.Product_Name" 
              placeholder="请输入货品名称/编号" 
              clearable 
              style="width: 150px; height: 32px;"
            />
          </el-form-item>
          <el-form-item label="货品类型">
            <el-select 
              v-model="formInline.Category_Name" 
              placeholder="请选择" 
              clearable
              style="width: 150px; height: 32px;"
            >
              <el-option label="电子产品" value="电子产品" />
              <el-option label="类别一1" value="类别一1" />
              <el-option label="告知好拼" value="告知好拼" />
              <el-option label="低值易耗品" value="低值易耗品" />
            </el-select>
          </el-form-item>
          <el-form-item label="单位">
            <el-select 
              v-model="formInline.Unit_Name" 
              placeholder="请选择" 
              clearable
              style="width: 150px; height: 32px;"
            >
              <el-option label="个" value="个" />
              <el-option label="米" value="米" />
              <el-option label="立方米" value="立方米" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="formInline.Status" 
              placeholder="请选择" 
              clearable
              style="width: 150px; height: 32px;"
            >
              <el-option label="正常" value="正常" />
              <el-option label="即将到期" value="即将到期" />
              <el-option label="已到期" value="已到期" />
            </el-select>
          </el-form-item>
  
          <!-- 第二行 -->
          <el-form-item label="仓库名称">
            <el-select 
              v-model="formInline.Warehouse_Name" 
              placeholder="请选择" 
              clearable
              style="width: 150px; height: 32px;"
            >
              <el-option label="仓库1" value="仓库1" />
              <el-option label="1号仓库" value="1号仓库" />
              <el-option label="2号仓库" value="2号仓库" />
              <el-option label="3号仓库" value="3号仓库" />
              <el-option label="4号仓库" value="4号仓库" />
              <el-option label="5号仓库" value="5号仓库" />
              <el-option label="666号仓库" value="666号仓库" />
            </el-select>
          </el-form-item>
          <el-form-item label="剩余天数">
            <el-input 
              v-model="formInline.RemainingDays" 
              placeholder="请输入剩余天数" 
              clearable
              style="width: 150px; height: 32px;"
            />
          </el-form-item>
          <el-form-item label="货品批次">
            <el-input 
              v-model="formInline.Batch" 
              placeholder="请输入批次" 
              clearable 
              style="width: 150px; height: 32px;"
            />
          </el-form-item>
          <el-form-item label="内部编码">
            <el-input 
              v-model="formInline.Internal_Code" 
              placeholder="请输入内部编码" 
              clearable 
              style="width: 150px; height: 32px;"
            />
          </el-form-item>
  
          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="success" @click="onSubmit" style="height: 32px;">查询</el-button>
            <el-button type="info" @click="resetForm" style="height: 32px; margin-left: 10px;">重置</el-button>
          </el-form-item>
        </el-form>
    </div>
  
    <div style="border: 1px solid #ccc; padding: 45px;">
      <!-- 表格操作按钮 -->
      <div style="margin-bottom: 15px; display: flex; justify-content: flex-end;">
        <el-button type="primary" @click="handleExport" style="margin-right: 10px;">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-button type="success" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
      
      <el-table 
         :data="tableData" 
         style="width: 100%"
         v-loading="loading"
         :max-height="500"
       >
          <el-table-column type="selection" width="55" fixed="left" />
          <el-table-column type="index" label="序号" width="60" fixed="left" />
          <el-table-column prop="product_Number" label="货品编号" width="120" fixed="left">
            <template #default="scope">
              <span class="product-number-link">{{ scope.row.product_Number }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="product_Name" label="货品名称" width="120" fixed="left" />
          <el-table-column prop="status" label="状态" width="100" fixed="left">
          </el-table-column>
          <el-table-column prop="category_Name" label="货品类型" width="100" />
          <el-table-column prop="specifications" label="规格" width="100" />
          <el-table-column prop="unit_Name" label="单位" width="80" />
          <el-table-column prop="warehouse_Name" label="仓库名称" width="100" />
          <el-table-column prop="storage_Name" label="仓位名称" width="100" />
          <el-table-column prop="internal_Code" label="内部编码" width="120" />
          <el-table-column prop="currentInventory" label="当前库存" width="100" />
          <el-table-column prop="batch" label="批次" width="80" />
          <el-table-column prop="createTime" label="生产日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="maturityDate" label="到期日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.maturityDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="expirationDate" label="保质期" width="120" />
          <el-table-column prop="remainingDays" label="剩余天数" width="100" />
          <el-table-column prop="warningDays" label="预警天数" width="100" />
        </el-table>
    </div>
        <!-- 分页控件 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="Page.PageIndex"
          v-model:page-size="Page.PageSize"
          :page-sizes="[15, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="Page.totalCount"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
  </template>
  <script lang="ts" setup>
  import { FinanceRed, StorageRed } from '@/http/axiosHelper';
  import { onMounted, reactive, ref } from 'vue'
  import { Download, Refresh } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  // import { StorageRed } from '@/http/axiosHelper'
  
  // 格式化日期函数
  const formatDate = (dateString: string) => {
    if (!dateString) return '';
    // 将ISO格式的日期字符串转换为本地格式
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  
  const formInline = reactive({
    Product_Name: '',
    Category_Name: '',
    Unit_Name:'',
    Internal_Code:'',
    Status:'',
    Batch:'',
    Warehouse_Name:'',
    RemainingDays:'',
  })
  
  const tableData = ref([]);
  const loading = ref(false);
  
  const Page = reactive({
    PageIndex: 1,
    PageSize: 15,
    totalCount: 0,
  })
  
  const onSubmit = () => 
  {
    loading.value = true;
    
    // 重置页码到第一页
    Page.PageIndex = 1;
    
    // 构建查询参数，过滤空值
    const params = {
      Product_Name: formInline.Product_Name || '',
      Category_Name: formInline.Category_Name || '',
      Unit_Name: formInline.Unit_Name || '',
      Internal_Code: formInline.Internal_Code || '',
      Status: formInline.Status || '',
      Batch: formInline.Batch || '',
      Warehouse_Name: formInline.Warehouse_Name || '',
      RemainingDays: formInline.RemainingDays || '',
      PageIndex: Page.PageIndex,
      PageSize: Page.PageSize
    };
  
    console.log('查询参数:', params);
  
    StorageRed.get("/api/WorkOrder/GetExpirationDate", { params })
      .then(res => {
        console.log('查询结果:', res);
        if (res.data && res.data.data) {
          tableData.value = res.data.data;
          Page.totalCount = res.data.totalCount || 0;
          console.log('设置表格数据:', tableData.value);
          console.log('设置总数:', Page.totalCount);
        } else {
          console.log('响应数据为空或格式不正确');
          tableData.value = [];
          Page.totalCount = 0;
        }
      })
      .catch(error => {
        console.error('查询失败:', error);
        console.error('错误详情:', error.response?.data);
        console.error('错误状态:', error.response?.status);
        tableData.value = [];
        Page.totalCount = 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }
  
  // 重置表单
  const resetForm = () => {
    formInline.Product_Name = '';
    formInline.Category_Name = '';
    formInline.Unit_Name = '';
    formInline.Internal_Code = '';
    formInline.Status = '';
    formInline.Batch = '';
    formInline.Warehouse_Name = '';
    formInline.RemainingDays = '';
    onSubmit();
  }
  
  // 处理页码变化
  const handleCurrentChange = (val: number) => {
    Page.PageIndex = val;
    onSubmit();
  }
  
  // 处理每页条数变化
  const handleSizeChange = (val: number) => {
    Page.PageSize = val;
    Page.PageIndex = 1; // 重置到第一页
    onSubmit();
  }
  
  // 导出数据
  // 导出函数（假设已配置 Axios 拦截器自动添加 Token）
  async function handleExport() {
      try {
          // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
          const response = await StorageRed({
              url: '/api/WorkOrder/GetExpirationDateExport', // 后端接口地址
              method: 'GET',
              params: {
                  PageIndex: Page.PageIndex,
                  PageSize: Page.PageSize,
                
              }, // 对应后端 [FromQuery] 的 command 参数
              responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
          });
  
          // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
          const fileName = getFileNameFromHeaders(response.headers);
  
          // 3. 生成下载链接并触发下载
          const blob = new Blob([response.data], {
              type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          });
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = fileName; // 文件名从响应头获取或自定义
          document.body.appendChild(a);
          a.click();
  
          // 4. 清理资源
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
  
      } catch (error: any) {
          // 处理错误（如后端返回 401/400 等）
          console.error('导出失败：', error.response?.data || error.message);
          alert('导出失败，请检查参数或重新登录');
      }
  }
  
  // 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
  function getFileNameFromHeaders(headers: any) {
      const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
      if (!contentDisposition) return '保质期查询表.xlsx'; // 默认文件名
  
      // 解码文件名（处理中文编码问题）
      const match = contentDisposition.match(/filename\*?=([^;]+)/);
      if (match) {
          return decodeURIComponent(match[1].replace(/["']/g, ''));
      }
      return '保质期查询表.xlsx';
  }
  
  // 刷新数据
  const refreshData = () => {
    console.log('刷新数据');
    onSubmit();
  }
  
  onMounted(() => {
    onSubmit();
  })
  </script>
  
  
  
  
  
  
  
  
  
  